package com.tanhua.dubbo.server.api.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VideoApi;
import com.tanhua.dubbo.server.enums.CommentType;
import com.tanhua.dubbo.server.enums.IdType;
import com.tanhua.dubbo.server.pojo.*;

import com.tanhua.dubbo.server.service.IdService;
import com.tanhua.dubbo.server.service.TimeLineService;
import com.tanhua.dubbo.server.vo.PageInfo;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

@Service(version = "1.0.0")
@Slf4j
public class QuanZiApiImpl implements QuanZiApi {

    //评论数据存储在Redis中key的前缀
    private static final String COMMENT_REDIS_KEY_PREFIX = "QUANZI_COMMENT_";
    //⽤是否点赞的前缀
    private static final String COMMENT_USER_LIEK_REDIS_KEY_PREFIX =
            "USER_LIKE_";
    //⽤是否喜欢的前缀
    private static final String COMMENT_USER_LOVE_REDIS_KEY_PREFIX =
            "USER_LOVE_";

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    @Autowired
    private TimeLineService timeLineService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private VideoApi videoApi;

    /**
     * 查询好友动态
     *
     * @param userId   用户id
     * @param page     当前页数
     * @param pageSize 每一页查询的条数
     * @return
     */
    @Override
    public PageInfo<Publish> queryPublishList(Long userId, Integer page, Integer pageSize) {
        // 查询好友动态，实际查询时间线表
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageSize(pageSize);
        pageInfo.setPageNum(page);
        //构造查询条件
        Query queryTimeLine = new Query();
        Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("date")));
        queryTimeLine.with(pageable);
        // 因为每个id都有自己的时间线表，所有使用表名称来区分
        List<TimeLine> timeLineList = this.mongoTemplate.find(queryTimeLine,
                TimeLine.class, "quanzi_time_line_" + userId);
        if (CollUtil.isEmpty(timeLineList)) {
            // 没有查询到数据
            return pageInfo;
        }
        // 获取时间线列表中的发布id的列表
        List<Object> ids = CollUtil.getFieldValues(timeLineList, "publishId");

        // 使用lambda表达式来获取IDS,根据动态id查询动态列表
        /*List<Object> ids = new ArrayList<>();
        for (TimeLine timeLine : timeLineList) {
            ids.add(timeLine.getPublishId());
        }*/
        //查询出发布信息id的信息集合，按照发布信息的时间降序
        Query queryPublish = Query.query(Criteria.where("id").in(ids))
                .with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = this.mongoTemplate.find(queryPublish, Publish.class);
        pageInfo.setRecords(publishList);

        return pageInfo;
    }

    /**
     * 发布动态
     *
     * @param publish
     * @return 发布成功返回动态id
     */
    @Override
    public String savePublish(Publish publish) {
        //对publish对象校验
        if (!ObjectUtil.isAllNotEmpty(publish.getText(), publish.getUserId())) {
            return null;
        }

        //设置主键id
        publish.setId(ObjectId.get());

        try {
            //设置自增长pid
            publish.setPid(idService.createId(IdType.PUBLISH));
            //设置创建时间
            publish.setCreated(System.currentTimeMillis());
            this.mongoTemplate.save(publish);
            //写入相册表
            Album album = new Album();
            album.setId(ObjectId.get());
            album.setPublishId(publish.getId());
            album.setCreated(publish.getCreated());

            this.mongoTemplate.save(album, "quanzi_album_" + publish.getUserId());

            //写入好友时间线表,异步写入
            this.timeLineService.saveTimeLine(publish.getUserId(), publish.getId());

        } catch (Exception e) {

            //TODO 需要做事务的回滚，Mongodb的单节点服务，不支持事务，对于回滚我们暂时不实现了
            log.error("发布动态失败！！publish = " + publish, e);
        }


        return publish.getId().toHexString();
    }

    /**
     * 查询推荐动态
     *
     * @param userId   用户id
     * @param page     当前页数
     * @param pageSize 每一页查询的数据条数
     * @return
     */
    @Override
    public PageInfo<Publish> queryRecommendPublishList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        String redisKey = "QUANZI_PUBLISH_RECOMMEND_" + userId;
        //查询推荐结果数据
        String data = redisTemplate.opsForValue().get(redisKey);
        if (StringUtils.isEmpty(data)) {
            return pageInfo;
        }

        //拿出各个pid，分页处理
        List<String> pidList = StrUtil.split(data, ',');
        int[] startEnd = PageUtil.transToStartEnd(page - 1, pageSize);
        int startIndex = startEnd[0];
        int endIndex = Math.min(startEnd[1], pidList.size());

        List<Long> pidLongList = new ArrayList<>();
        for (int i = startIndex; i < endIndex; i++) {
            pidLongList.add(Long.valueOf(pidList.get(i)));
        }

        if (CollUtil.isEmpty(pidLongList)) {
            return pageInfo;
        }

        Query query = Query.query(Criteria.where("pid").in(pidLongList))
                .with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = this.mongoTemplate.find(query, Publish.class);


        pageInfo.setRecords(publishList);

        return pageInfo;
    }

    /**
     * 根据id查询动态
     *
     * @param id 动态id
     * @return
     */
    @Override
    public Publish queryPublishById(String id) {
        return this.mongoTemplate.findById(new ObjectId(id), Publish.class);
    }

    /**
     * 动态点赞
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean likeComment(Long userId, String publishId) {
        //在Redis中查询是否点赞
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String userHashKey = this.getCommentUserLikeRedisKeyPrefix(userId);
        //判断该用户是否点赞，如果已经点赞直接返回
        Boolean flag = this.queryUserIsLike(userId, publishId);
        if (flag) {
            return false;
        }
        //保存Comment数据
        Boolean result = this.saveComment(userId, publishId, CommentType.LIKE, null);
        if (!result) {
            return false;
        }
        //修改redis中的点赞数以及是否点赞
        //点赞数加1
        String hashKey = CommentType.LIKE.toString();
        this.redisTemplate.opsForHash().increment(redisKey, hashKey, 1);

        //修改是否点赞
        this.redisTemplate.opsForHash().put(redisKey, userHashKey, "1");

        return true;
    }

    /**
     * 取消动态点赞
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean disLikeComment(Long userId, String publishId) {
        //判断是否点赞
        Boolean code = this.queryUserIsLike(userId, publishId);
        if (!code) {
            //没有点赞，直接返回
            return false;
        }
        //有点赞，删除点赞数据
        boolean result = this.removeComment(userId, publishId, CommentType.LIKE);
        if (!result) {
            return false;
        }

        //修改Redis中的数据
        String redisKey = this.getCommentRedisKeyPrefix(publishId) + userId;
        String hashKey = CommentType.LIKE.toString();
        String userHashKey = this.getCommentUserLikeRedisKeyPrefix(userId);

        //修改点赞数
        this.redisTemplate.opsForHash().increment(redisKey, hashKey, -1);

        //用户是否点赞
        this.redisTemplate.opsForHash().delete(redisKey, userHashKey);

        return true;
    }

    /**
     * 点赞数
     *
     * @param publishId
     * @return
     */
    @Override
    public Long queryLikeCount(String publishId) {
        //从Redis中命中查询，如果命中直接返回即可

        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();
        Object data = this.redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(data)) {
            return Convert.toLong(data);
        }

        //没有信息，从MongoDB中查询
        long count = this.queryCommentCount(publishId, CommentType.LIKE);
        /*Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(CommentType.LIKE));
        long count = this.mongoTemplate.count(query, Comment.class);*/

        //将查询到的数据写入Redis中
        this.redisTemplate.opsForHash().put(redisKey, hashKey, String.valueOf(count));
        return count;
    }

    /**
     * 查询用户是否点赞该动态
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean queryUserIsLike(Long userId, String publishId) {

        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String userHashKey = this.getCommentUserLikeRedisKeyPrefix(userId);
        //从redis中查询数据
        Object data = this.redisTemplate.opsForHash().get(redisKey, userHashKey);
        if (ObjectUtil.isNotEmpty(data)) {
            //查询到数据不为空，返回
            //Convert.toStr(data) 转为字符串
            return StrUtil.equals(Convert.toStr(data), "1");
        }
        //查询Mongodb，确定是否已经点赞
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("userId").is(userId)
                .and("commentType").is(CommentType.LIKE)
        );
        long count = this.mongoTemplate.count(query, Comment.class);
        if (count == 0) {
            //没有点赞
            return false;
        }

        this.redisTemplate.opsForHash().put(redisKey, userHashKey, "1");
        return true;
    }

    /**
     * 喜欢
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean loveComment(Long userId, String publishId) {
        //查看当前用户是否喜欢该动态
        Boolean result = this.queryUserIsLove(userId, publishId);
        if (result) {
            return false;
        }
        //保存Comment数据
        Boolean flag = this.saveComment(userId, publishId, CommentType.LOVE, null);
        if (!flag) {
            //保存失败
            return false;
        }

        //修改redis中的喜欢数以及是否喜欢
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LOVE.toString();
        //喜欢数加1
        this.redisTemplate.opsForHash().increment(redisKey, hashKey, 1);
        //标记用户已经喜欢
        String userHashKey = this.getCommentUserLoveRedisKey(userId);
        this.redisTemplate.opsForHash().put(redisKey, userHashKey, "3");
        return true;
    }

    /**
     * 取消喜欢
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean disLoveComment(Long userId, String publishId) {
        //查看当前用户是否喜欢
        Boolean result = this.queryUserIsLove(userId, publishId);
        if (!result) {
            //不喜欢，返回
            return false;
        }
        //删除当前喜欢信息
        boolean flag = this.removeComment(userId, publishId, CommentType.LOVE);
        if (!flag) {
            //删除失败
            return false;
        }
        //删除当前在Redis中的信息
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LOVE.toString();
        String userHashKey = this.getCommentUserLoveRedisKey(userId);
        //修改记录数
        this.redisTemplate.opsForHash().increment(redisKey, hashKey, -1);
        //删除Redis中标记的喜欢
        this.redisTemplate.opsForHash().delete(redisKey, userHashKey);
        return true;
    }

    /**
     * 查询喜欢数
     *
     * @param publishId
     * @return
     */
    @Override
    public Long queryLoveCount(Long userId, String publishId) {
        //现在Redis中查找，未查到想关信息后去MongoDB中查找
        //⾸先从redis中命中，如果命中的话就返回，没有命中就查询Mongodb
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LOVE.toString();
        Object data = this.redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(data)) {
            return Convert.toLong(data);
        }

       /* Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("userId").is(userId)
                .and("commentType").is(CommentType.LOVE.getType()));
        long count = this.mongoTemplate.count(query, Comment.class);*/
        long count = this.queryCommentCount(publishId, CommentType.LOVE);
        //存储到redis中
        this.redisTemplate.opsForHash().put(redisKey, hashKey, String.valueOf(count));
        return count;
    }

    /**
     * 查询用户是否喜欢该动态
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean queryUserIsLove(Long userId, String publishId) {
        //⾸先从redis中命中，如果命中的话就返回，没有命中就查询Mongodb
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LOVE.toString();
        Object data = this.redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(data)) {
            return StrUtil.equals(Convert.toStr(data), "3");
        }
        //查询MongoDB

        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("userId").is(userId)
                .and("commentType").is(CommentType.LOVE.getType()));
        this.mongoTemplate.count(query, Comment.class);
        //标记用户已经喜欢
        this.redisTemplate.opsForHash().put(redisKey, hashKey, "3");
        return true;
    }

    /**
     * 查询评论
     *
     * @param publishId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Comment> queryCommentList(String publishId, Integer page, Integer pageSize) {
        PageInfo<Comment> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        //PageRequest是Pageable的实现类
        Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.asc("created")));
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(CommentType.COMMENT.getType())).with(pageable);
        List<Comment> commentList = this.mongoTemplate.find(query, Comment.class);
        //填充pageInfo
        pageInfo.setRecords(commentList);
        return pageInfo;
    }

    /**
     * 发表评论
     *
     * @param userId
     * @param publishId
     * @param content
     * @return
     */
    @Override
    public Boolean saveComment(Long userId, String publishId, String content) {
        return this.saveComment(userId, publishId, CommentType.COMMENT, content);
    }

    /**
     * 查询评论数
     *
     * @param publishId
     * @return
     */
    @Override
    public Long queryCommentCount(String publishId) {
        return this.queryCommentCount(publishId, CommentType.COMMENT);
    }

    /**
     * 查看对自己的点赞列表
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Comment> queryLikeCommentListByUser(Long userId, Integer page, Integer pageSize) {
        PageInfo<Comment> pageInfo = this.queryCommentListByUser(userId,CommentType.LIKE, page, pageSize);
        return pageInfo;
    }

    /**
     * 查看对自己的喜欢列表
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Comment> queryLoveCommentListByUser(Long userId, Integer page, Integer pageSize) {

        return this.queryCommentListByUser(userId,CommentType.LOVE, page, pageSize);
    }

    /**
     * 查看对自己的评论列表
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Comment> queryCommentListByUser(Long userId, Integer page, Integer pageSize) {
        return this.queryCommentListByUser(userId,CommentType.COMMENT, page, pageSize);
    }

    /**
     * 查询相册表
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Publish> queryAlbumList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        PageRequest pageRequest = PageRequest.of(page, pageSize,
                Sort.by(Sort.Order.desc("created")));
        Query query = new Query().with(pageRequest);
        List<Album> albums = this.mongoTemplate.find(query, Album.class, "quanzi_album_" + userId);
        if (CollUtil.isEmpty(albums)){
            return pageInfo;
        }
        List<Object> publishIds = CollUtil.getFieldValues(albums, "publishId");

        Query queryPublish = Query.query(Criteria.where("id").in(publishIds))
                .with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = this.mongoTemplate.find(queryPublish, Publish.class);

        pageInfo.setRecords(publishList);

        return pageInfo;
    }

    /**
     * 该动态有的评论数
     *
     * @param publishId
     * @param commentType
     * @return
     */
    private Long queryCommentCount(String publishId, CommentType commentType) {
        Query query = Query.query(Criteria.where("publishId").is(new
                ObjectId(publishId))
                .and("commentType").is(commentType.getType())
        );
        return this.mongoTemplate.count(query, Comment.class);
    }

    /**
     * 获取用户是否点赞,在Redis中的key(大key)
     *
     * @param publishId
     * @return
     */
    private String getCommentRedisKeyPrefix(String publishId) {
        return COMMENT_REDIS_KEY_PREFIX + publishId;
    }

    /**
     * 获取用户是否点赞,在Redis中的key(hash中的key)
     *
     * @param userId
     * @return
     */
    private String getCommentUserLikeRedisKeyPrefix(Long userId) {
        return COMMENT_USER_LIEK_REDIS_KEY_PREFIX + userId;
    }

    /**
     * 获取用户是否喜欢，在Redis中的key
     *
     * @param userId
     * @return
     */
    private String getCommentUserLoveRedisKey(Long userId) {
        return COMMENT_USER_LOVE_REDIS_KEY_PREFIX + userId;
    }

    /**
     * 保存数据
     *
     * @param userId
     * @param publishId
     * @param commentType //评论类型，1-点赞，2-评论，3-喜欢
     * @param content     //评论内容
     * @return
     */
    private Boolean saveComment(Long userId, String publishId,
                                CommentType commentType, String content) {

        try {
            Comment comment = new Comment();
            comment.setId(ObjectId.get());
            //评论类型
            comment.setCommentType(commentType.getType());
            //评论内容
            comment.setContent(content);
            //当前动态的id
            comment.setPublishId(new ObjectId(publishId));
            //评论人的id
            comment.setUserId(userId);
            Publish publish = this.queryPublishById(publishId);
            if (ObjectUtil.isNotEmpty(publish)) {
                //发布当前动态的user的id
                comment.setPublishUserId(publish.getUserId());
            } else {
                //查询评论
                Comment myComment = this.queryCommentById(publishId);
                if (ObjectUtil.isNotEmpty(myComment)) {
                    comment.setPublishUserId(myComment.getUserId());
                } else {
                    //查询小视频
                    Video video = this.videoApi.queryVideoById(publishId);
                    if (ObjectUtil.isNotEmpty(video)) {
                        comment.setPublishUserId(video.getUserId());
                    } else {
                        //其他情况
                        return false;
                    }
                }
            }

            //保存到MongoDB中
            this.mongoTemplate.save(comment);
            return true;
        } catch (Exception e) {
            log.error("保存comment信息失败！！！ userId = " + userId + ", publishId = " +
                    publishId + ", commentType = " + commentType, e);
        }
        return false;
    }

    /**
     * 查询评论
     *
     * @param publishId
     * @return
     */
    private Comment queryCommentById(String publishId) {
        return this.mongoTemplate.findById(new ObjectId(publishId), Comment.class);
    }

    /**
     * 删除评论
     *
     * @param userId
     * @param publishId
     * @param commentType
     * @return
     */
    private boolean removeComment(Long userId, String publishId, CommentType commentType) {


        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("publishId").is(new ObjectId(publishId))
                .and("commentType").is(commentType.getType())
        );
        long count = this.mongoTemplate.remove(query, Comment.class).getDeletedCount();
        boolean flag = count > 0;
        System.out.println(flag);
        return flag;
    }

    /**
     * 根据userId，commentType查询评论（包括喜欢，点赞）表
     * @param userId
     * @param commentType
     * @param page
     * @param pageSize
     * @return
     */
    private PageInfo<Comment> queryCommentListByUser(Long userId, CommentType commentType, Integer page, Integer pageSize) {
        PageInfo<Comment> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        PageRequest pageRequest = PageRequest.of(page, pageSize, Sort.by(Sort.Order.desc("created")));
        /*Query query = Query.query(Criteria.where("publishUserId").is(userId)
                .and("commentType").is(commentType.getType())).with(pageRequest);*/
        int type = commentType.getType();

        System.out.println(commentType.getType());
        Query query = new Query(Criteria
                .where("publishUserId").is(userId)
                .and("commentType").is(commentType.getType())).with(pageRequest);
        List<Comment> commentList = this.mongoTemplate.find(query, Comment.class);
        pageInfo.setRecords(commentList);
        return pageInfo;
    }
}
